package com.xianyuwangyou.taizhangdengji

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.Button
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.MenuAnchorType
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

// 产品信息数据类
data class ProductEntry(
    val product: String,
    val secondaryProduct: String, // 二级产品名称
    val unit: String, // 单位
    val amount: String,
    val notes: String
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AccountEntryScreen(
    onNavigateBack: () -> Unit,
    modifier: Modifier = Modifier
) {
    // 获取配置数据管理器实例
    val configDataManager = ConfigDataManager.getInstance()
    val dataManager = AccountDataManager.getInstance()
    val context = LocalContext.current
    
    // 获取营销员和产品列表
    val marketers = configDataManager.getMarketers()
    val products = configDataManager.getProducts()
    
    var marketer by remember { mutableStateOf(if (marketers.isNotEmpty()) marketers[0] else "") }
    var date by remember { 
        mutableStateOf(SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())) 
    }
    
    // 产品信息列表状态，至少有一个产品信息项
    var productEntries by remember { 
        mutableStateOf(
            listOf(
                ProductEntry(
                    product = if (products.isNotEmpty()) products[0] else "",
                    secondaryProduct = "",
                    unit = "",
                    amount = "",
                    notes = ""
                )
            )
        ) 
    }
    
    var isMarketerMenuExpanded by remember { mutableStateOf(false) }
    
    // 添加滚动状态
    val scrollState = rememberScrollState()
    
    Scaffold(
        modifier = modifier.fillMaxSize(),
        topBar = {
            TopAppBar(
                title = { Text("台账登记") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .background(Color(0xFFF5F5F5)) // 添加灰色背景
                .padding(16.dp)
                .verticalScroll(scrollState) // 添加垂直滚动功能
        ) {
            // 独立卡片1：营销员和日期
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = Color.White
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    // 营销员下拉菜单
                    ExposedDropdownMenuBox(
                        expanded = isMarketerMenuExpanded,
                        onExpandedChange = { isMarketerMenuExpanded = it }
                    ) {
                        TextField(
                            readOnly = true,
                            value = marketer,
                            onValueChange = { },
                            label = { Text("营销员") },
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = isMarketerMenuExpanded) },
                            modifier = Modifier
                                .menuAnchor(MenuAnchorType.PrimaryNotEditable)
                                .fillMaxWidth(),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            )
                        )
                        ExposedDropdownMenu(
                            expanded = isMarketerMenuExpanded,
                            onDismissRequest = { isMarketerMenuExpanded = false },
                            containerColor = Color.White // 设置下拉菜单背景为白色
                        ) {
                            marketers.forEach { item ->
                                Text(
                                    text = item,
                                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 16.dp, vertical = 8.dp)
                                        .clickable { 
                                            marketer = item
                                            isMarketerMenuExpanded = false
                                        }
                                )
                            }
                        }
                    }
                    
                    TextField(
                        value = date,
                        onValueChange = { date = it },
                        label = { Text("日期") },
                        modifier = Modifier
                            .fillMaxWidth(),
                        colors = TextFieldDefaults.colors(
                            focusedContainerColor = Color.Transparent,
                            unfocusedContainerColor = Color.Transparent,
                            disabledContainerColor = Color.Transparent
                        )
                    )
                }
            }
            
            // 独立卡片2：产品信息列表
            productEntries.forEachIndexed { index, entry ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 16.dp),
                    colors = CardDefaults.cardColors(
                        containerColor = Color.White
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "产品信息 ${index + 1}",
                                style = androidx.compose.material3.MaterialTheme.typography.titleMedium
                            )
                            
                            // 只有当有多个产品信息项时才显示删除按钮
                            if (productEntries.size > 1) {
                                IconButton(
                                    onClick = {
                                        productEntries = productEntries.toMutableList().apply { removeAt(index) }
                                    }
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Delete,
                                        contentDescription = "删除"
                                    )
                                }
                            }
                        }
                        
                        var isProductMenuExpanded by remember { mutableStateOf(false) }
                        
                        // 产品名称下拉菜单
                        ExposedDropdownMenuBox(
                            expanded = isProductMenuExpanded,
                            onExpandedChange = { isProductMenuExpanded = it }
                        ) {
                            TextField(
                                readOnly = true,
                                value = entry.product,
                                onValueChange = { },
                                label = { Text("产品名称") },
                                trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = isProductMenuExpanded) },
                                modifier = Modifier
                                    .menuAnchor(MenuAnchorType.PrimaryNotEditable)
                                    .fillMaxWidth(),
                                colors = TextFieldDefaults.colors(
                                    focusedContainerColor = Color.Transparent,
                                    unfocusedContainerColor = Color.Transparent,
                                    disabledContainerColor = Color.Transparent
                                )
                            )
                            ExposedDropdownMenu(
                                expanded = isProductMenuExpanded,
                                onDismissRequest = { isProductMenuExpanded = false },
                                containerColor = Color.White // 设置下拉菜单背景为白色
                            ) {
                                products.forEach { item ->
                                    Text(
                                        text = item,
                                        style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(horizontal = 16.dp, vertical = 8.dp)
                                            .clickable { 
                                                // 更新对应索引的产品信息
                                                productEntries = productEntries.toMutableList().apply {
                                                    this[index] = this[index].copy(product = item)
                                                }
                                                isProductMenuExpanded = false
                                            }
                                    )
                                }
                            }
                        }
                        
                        // 添加二级产品名称下拉菜单
                        var isSecondaryProductMenuExpanded by remember { mutableStateOf(false) }
                        val secondaryProducts = configDataManager.getSecondaryProducts(entry.product)
                        
                        ExposedDropdownMenuBox(
                            expanded = isSecondaryProductMenuExpanded,
                            onExpandedChange = { isSecondaryProductMenuExpanded = it }
                        ) {
                            TextField(
                                readOnly = true,
                                value = entry.secondaryProduct,
                                onValueChange = { },
                                label = { Text("二级产品名称") },
                                trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = isSecondaryProductMenuExpanded) },
                                modifier = Modifier
                                    .menuAnchor(MenuAnchorType.PrimaryNotEditable)
                                    .fillMaxWidth(),
                                colors = TextFieldDefaults.colors(
                                    focusedContainerColor = Color.Transparent,
                                    unfocusedContainerColor = Color.Transparent,
                                    disabledContainerColor = Color.Transparent
                                )
                            )
                            ExposedDropdownMenu(
                                expanded = isSecondaryProductMenuExpanded,
                                onDismissRequest = { isSecondaryProductMenuExpanded = false },
                                containerColor = Color.White // 设置下拉菜单背景为白色
                            ) {
                                secondaryProducts.forEach { item ->
                                    Text(
                                        text = item,
                                        style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(horizontal = 16.dp, vertical = 8.dp)
                                            .clickable { 
                                                // 更新对应索引的产品信息
                                                productEntries = productEntries.toMutableList().apply {
                                                    this[index] = this[index].copy(secondaryProduct = item)
                                                }
                                                isSecondaryProductMenuExpanded = false
                                            }
                                    )
                                }
                            }
                        }
                        
                        TextField(
                            value = entry.amount,
                            onValueChange = { newValue ->
                                // 更新对应索引的产品信息
                                productEntries = productEntries.toMutableList().apply {
                                    this[index] = this[index].copy(amount = newValue)
                                }
                            },
                            label = { Text("数量") },
                            modifier = Modifier
                                .fillMaxWidth(),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            )
                        )
                        
                        // 添加单位输入框
                        /*
                        TextField(
                            value = entry.unit,
                            onValueChange = { newValue ->
                                // 更新对应索引的产品信息
                                productEntries = productEntries.toMutableList().apply {
                                    this[index] = this[index].copy(unit = newValue)
                                }
                            },
                            label = { Text("单位") },
                            modifier = Modifier
                                .fillMaxWidth(),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            )
                        )
                        */
                        
                        TextField(
                            value = entry.notes,
                            onValueChange = { newValue ->
                                // 更新对应索引的产品信息
                                productEntries = productEntries.toMutableList().apply {
                                    this[index] = this[index].copy(notes = newValue)
                                }
                            },
                            label = { Text("备注") },
                            modifier = Modifier
                                .fillMaxWidth(),
                            colors = TextFieldDefaults.colors(
                                focusedContainerColor = Color.Transparent,
                                unfocusedContainerColor = Color.Transparent,
                                disabledContainerColor = Color.Transparent
                            )
                        )
                    }
                }
            }
            
            // 添加产品信息按钮
            Button(
                onClick = {
                    productEntries = productEntries.toMutableList().apply {
                        add(
                            ProductEntry(
                                product = if (products.isNotEmpty()) products[0] else "",
                                secondaryProduct = "",
                                unit = "",
                                amount = "",
                                notes = ""
                            )
                        )
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp),
                colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                    containerColor = Color.White
                )
            ) {
                Icon(imageVector = Icons.Default.Add, contentDescription = null, tint = Color.Black)
                Text("添加产品信息", color = Color.Black)
            }
            
            // 保存按钮
            Button(
                onClick = {
                    // 保存台账记录的逻辑
                    try {
                        // 验证输入
                        if (marketer.isBlank()) {
                            Toast.makeText(context, "请选择营销员", Toast.LENGTH_SHORT).show()
                            return@Button
                        }
                        
                        var hasValidEntry = false
                        
                        // 验证每个产品信息项
                        for ((index, entry) in productEntries.withIndex()) {
                            if (entry.product.isBlank()) {
                                Toast.makeText(context, "请选择第${index + 1}项的产品名称", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            if (entry.amount.isBlank()) {
                                Toast.makeText(context, "请输入第${index + 1}项的数量", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            val amountValue = entry.amount.toIntOrNull()
                            if (amountValue == null) {
                                Toast.makeText(context, "第${index + 1}项的数量必须是有效数字", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                            
                            hasValidEntry = true
                        }
                        
                        if (!hasValidEntry) {
                            Toast.makeText(context, "至少需要添加一个产品信息", Toast.LENGTH_SHORT).show()
                            return@Button
                        }
                        
                        // 为每个产品信息创建台账记录
                        for (entry in productEntries) {
                            val amountValue = entry.amount.toInt()
                            
                            // 创建新的台账记录
                            val newRecord = AccountRecord(
                                id = (System.currentTimeMillis() % Int.MAX_VALUE.toLong()).toInt(), // 使用当前时间作为ID，避免负数
                                marketer = marketer,
                                product = entry.product,
                                secondaryProduct = entry.secondaryProduct, // 二级产品名称
                                amount = amountValue,
                                date = date,
                                notes = entry.notes
                            )
                            
                            // 保存记录
                            dataManager.addAccountRecordAndSave(newRecord, context)
                        }
                        
                        // 显示成功消息
                        Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show()
                        
                        // 重置表单字段
                        marketer = if (marketers.isNotEmpty()) marketers[0] else ""
                        date = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date())
                        productEntries = listOf(
                            ProductEntry(
                                product = if (products.isNotEmpty()) products[0] else "",
                                secondaryProduct = "",
                                unit = "",
                                amount = "",
                                notes = ""
                            )
                        )
                        
                        // 返回上一页
                        onNavigateBack()
                    } catch (e: Exception) {
                        Toast.makeText(context, "保存失败: ${e.message}", Toast.LENGTH_SHORT).show()
                        e.printStackTrace()
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
                    .padding(bottom = 16.dp), // 添加底部内边距，确保按钮不会紧贴屏幕底部
                colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                    containerColor = Color(0xFF019883) // 修改为指定颜色
                )
            ) {
                Text("保存")
            }
        }
    }
}